from rest_framework.views import APIView
import re
from . import Serializers,models
from django.core.cache import cache
from utils.response import APIResponse
from libs.tx_sms.sms import *
from django.conf import settings

#多方式登录
class LoginAPIView(APIView):
    def post(self,request,*args,**kwargs):
        serializer = Serializers.LoginModelSerializer(data = request.data)
        serializer.is_valid(raise_exception=True)
        return APIResponse(data={
            'username':serializer.user.username,
            'token': serializer.token
        })
#手机号验证是否注册
class CheckMobileAPIView(APIView):
#     手机号验证是否登录
    def post(self,request,*args,**kwargs):
        mobile = request.data.get('mobile')
        if re.match('^1\d{10}$',mobile):
            if not models.User.objects.filter(mobile=mobile).first():
                return APIResponse(data_status='该账号可以注册')          #此处代码可以整合
            else:
                return APIResponse(data_msg='该账号已经被注册',data_status=1)
        else:
            return APIResponse(data_msg='手机号格式错误',data_status=1)


#验证码获取接口
class SMSAPIView(APIView):
    authentication_classes = []
    permission_classes = []
    def post(self,request,*args,**kwargs):
        mobile = request.data.get('mobile')
        if not (mobile and re.match(r'^1[3-9][0-9]{9}$',mobile)):
            return APIResponse(data_status=1,data_msg='手机号码格式错误')
        elif not models.User.objects.filter(mobile=mobile).first():
            return APIResponse(data_status=1,data_msg='该手机号未进行注册')
        code = get_code()
        exc = settings.SMS_EXC
        result = send_sms(mobile,code,exc)
        if result:
            cache.set(settings.CHECK_PREFIX_KEY % mobile,code,settings.SMS_EXC)
            print(11111,cache.get(settings.CHECK_PREFIX_KEY % mobile))
            return APIResponse()
        else:
            return APIResponse(data_status=1,data_msg='验证码发送失败')



#手机验证码登录接口
'''
    手机号,验证码  在登录之前 验证手机号是否已经注册  不需要密码  在serializer中验证验证码是否正确  手机号是否正确
'''
class MobileLoginAPIView(APIView):
    authentication_classes = []
    permission_classes = []
    def post(self,request,*args,**kwargs):
        user_ser = Serializers.MobileLoginModelSerializer(data=request.data)
        user_ser.is_valid(raise_exception=True)
        print(user_ser)
        return APIResponse(data={
            'user' : user_ser.user.username,
            'token' : user_ser.token
        })




#手机验证码注册接口
class RegisterAPIView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self,request,*args,**kwargs):
        user_ser = Serializers.RegisterMobileSerializer(data=request.data)
        user_ser.is_valid(raise_exception=True)
        user_ser.save()
        return APIResponse()








